package cn.tedu.sp11.fallback;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

//访问ItemService时失败了 就执行降级的代码
@Component
public class ItemServiceFallback implements FallbackProvider {

    @Override    //要返回serviceId，表示这个降级类响应的信息是针对哪个服务的
    public String getRoute() {

        return "item-service";
        //return "*";  这两种写法都是 说明 无论调用哪个服务失败了，都会返回对应的FB方法结果
        //return null;
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        //返回降级方法响应的内容
        //在response对象中，要设置http协议的状态码，协议头，协议体

                //匿名内部类
        return new ClientHttpResponse() {

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {
                //空着 不用写
            }

            @Override      //协议体
            public InputStream getBody() throws IOException {
                //JsonResult---{}

                String json = JsonResult.err().msg("调用商品后台服务器服务失败").toString();

                ByteArrayInputStream byteArrayInputStream =  new ByteArrayInputStream(json.getBytes("UTF-8"));

                return byteArrayInputStream;
            }

            @Override     //协议头
            public HttpHeaders getHeaders() {
                //Content-Type :
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
